<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/7/16
 * Time: 下午12:33
 */

namespace app\admin\logic;


use app\model\ExpressCompany;
use extend\Functions;
use extend\STATUS_CODE;
use think\facade\Log;

class Express
{
    /**
     * @purpose 接收快递100订单物流数据推送
     * @param $data
     * @return array
     * @throws \think\exception\PDOException
     */
    public static function subscribeCallback ($data)
    {
        Log::write('快递100订阅推送数据:'. json_encode($data), 'notice');
        // 获取物流单号
        $express_num        = $data['lastResult']['nu'];
        // 获取物流状态
        $express_state      = $data['lastResult']['state'];
        // 是否签收
        $is_check           = $data['lastResult']['ischeck'];
        $express_code       = $data['lastResult']['com'];
        $express_data       = $data['lastResult']['data'];

        $order              = new \app\model\Order();
        $express            = new \app\model\Express();

        $order->startTrans();
        $order_no           = $order
            ->where([
                'express_no'    => $express_num,
                'express_code'  => $express_code
            ])
            ->value('order_no');
        if (!$order_no) {
            $order->rollback();
            return [
                'result'        => false,
                'returnCode'    => 301,
                'message'       => '失败'
            ];
        }
        $update_order_state = true;
        if ((int) $is_check === 1) {
            $update_order_state = $order
                ->save(['status' => 8], ['order_no' => $order_no]);
        }
        $express_insert_data                    = [];
        $express_insert_data['order_no']      = $order_no;
        $express_insert_data['number']          = $express_num;
        $express_insert_data['express_company_code']          = $express_code;
        $express_insert_data['state']           = $express_state;
        $express_insert_data['is_check']        = $is_check;
        $express_insert_data['process']            = $express_data;
        if ($express->where(['order_no' => $order_no])->count(1) > 0) {
            $express_result = $express
                ->save($express_insert_data, ['order_no' => $order_no]);
        } else {
            $express_result = $express
                ->data($express_insert_data)
                ->save();
        }
        if ($express_result && $update_order_state) {
            $order->commit();
            return [
                'result'        => true,
                'returnCode'    => 200,
                'message'       => '成功'
            ];
        }
        $order->rollback();
        return [
            'result'        => false,
            'returnCode'    => 300,
            'message'       => '失败'
        ];
    }

    /**
     * @purpose 订阅快递
     * @param $param
     * @return mixed|\Requests_Response|string
     */
    public static function subscribe ($param)
    {

//        $data               = [];
//        $data['schema']     = 'json';
//        $_param             = [];
//        $_param['company']  = $param['company'];
//        $_param['number']   = $param['number'];
//        $_param['key']      = config('express100.key');
//        if (isset($param['from'])) {
//            $_param['from'] = $param['from'];
//        }
//        if (isset($param['to'])) {
//            $_param['to']   = $param['to'];
//        }
//        $_param['parameters']['callbackurl'] =  config('express100.subscribe_callback');
//        $data['param']      = $_param;
//        Log::write('订阅快递100提交数据:'.$param['number'].':'. json_encode($data), 'notice');
//        $result             = \Requests::post(config('express100.subscribe'), [], $data, [
//            'proxy' => '127.0.0.1:8888',
//        ]);
//        $result             = $result->body;
//        Log::write('订阅响应数据'. $result, 'notice');
//        $result             = json_decode($result, true);

        $post_data = array();
        $post_data["schema"] = 'json' ;
        //callbackurl请参考callback.php实现，key经常会变，请与快递100联系获取最新key
        $post_data["param"] = '{"company":"'
            .$param['company'].'", "number":"'
            .$param['number'].'","key":"'
            .config('express100.key')
            .'", "parameters":{"callbackurl":"'
            .config('express100.subscribe_callback')
            .'"}}';

//        $url='http://www.kuaidi100.com/poll';

        $o="";
        foreach ($post_data as $k=>$v)
        {
            $o.= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
        }

        $post_data=substr($o,0,-1);

        Log::write('订阅数据:'. $post_data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,config('express100.subscribe'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);		//返回提交结果，格式与指定的格式一致（result=true代表成功）
        curl_close($ch);
        return json_decode($result, true);
    }
    /**
     * @purpose 获取快递公司列表
     * @param array $where
     * @param int $page
     * @param int $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function items (
        array $where = [],
        int $page = 1,
        int $size = 40): array
    {
        $model       = new ExpressCompany();
        $result      = $model
            ->field('id,name,code,sort,is_default')
            ->where($where)
            ->page($page, $size)
            ->select();
        $total  = $model->total($where);
        return Functions::result(
            STATUS_CODE::SUCCESS,
            [
                'total' => $total,
                'list'  => $result
            ]
        );
    }

    /**
     * @purpose 设置默认发货快递公司
     * @param int $id
     * @return array
     */
    public static function setDefault (int $id): array
    {
        $model      = new ExpressCompany();
        ExpressCompany::where('id','>', 0)->update(['is_default' => 1]);
        $model
            ->isUpdate(true)
            ->save(['is_default' => 2], ['id' => $id]);
        return Functions::result(
            STATUS_CODE::SUCCESS
        );
    }

    /**
     * @purpose 获取默认发货快递
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getDefault (): array
    {
        $model      = new ExpressCompany();
        $result     = $model
            ->where('is_default', 2)
            ->field('name,code')
            ->find();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }

    /**
     * @purpose 搜索快递公司
     * @param string $kw
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function search(string $kw = ''): array
    {
        if (!$kw) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '请输入快递公司名字进行搜索'
            );
        }
        $where   = [];
        $where[] = ['name', ['like', '%'.$kw],['like', '%'.$kw.'%'],['like', $kw.'%'], 'or'];
        $model   = new ExpressCompany();
        $result  = $model
            ->where($where)
            ->field('id,name,code')
            ->select();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }
}